#include <REGX52.H>

unsigned int timer_seed = 0x1234;

unsigned int timer_rand()
{
    timer_seed = (timer_seed * 12345 + 67890) % 65535;
    return timer_seed;
}

unsigned int get_timer0_value()
{
    unsigned char high, low;

    do
    {
        high = TH0;
        low = TL0;
    } while (high != TH0);

    // (high << 8) 表达式数据类型是int
    return (high << 8) | low;
}

void update_timer_seed()
{
    timer_seed = get_timer0_value();
}

void timer0_init()
{
    // timer0 模式1: 使用TH0+TL0 计数
    TMOD &= 0xF0;
    TMOD |= 0x01;

    // 启动Timer0，启动之后TH0+TL0计数
    TR0 = 1;
    // timer0的中断使能
    ET0 = 0;
    // 中断总开关
    EA = 1;
    // 调整中断优先级，需要在timer0中断调用串口打印设置优先级
    PT0 = 1;
}

void timer0_isr_on()
{
    ET0 = 1;
}

void timer0_isr_off()
{
    ET0 = 0;
}